package com.zanha.javacmsframework.controller.admin;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import org.osgl.http.H;
import org.osgl.mvc.annotation.Before;
import org.osgl.web.util.UserAgent;
import com.zanha.javacmsframework.controller.Global;
import com.zanha.javacmsframework.logic.PermissionsLogic;
import com.zanha.javacmsframework.model.authority.AdminsModel;
import com.zanha.javacmsframework.util.*;
import act.app.ActionContext;
import act.controller.Controller;
import act.controller.Controller.Util;
import act.db.ebean.EbeanDao;

@Controller("/admin")
public class Base extends Global{
	//不需要权限验证的action
	private List<String> noPermissonActions = new ArrayList<String>();
	
	@Inject
    private H.Session session;	
	
	@Inject
	ActionContext context;
	
	@Inject
	private UserAgent ua;
	
	@Inject 
	private PermissionsLogic permissionsLogic;
	
	@Inject
	private Permissions permissions;
	
	@Inject
    private EbeanDao<Integer,AdminsModel> adminsDao;
	
	//登陆信息啦
	public AdminsModel loginAdmin;
	
	public String __PPPERFIX__;
	
	public String __ASSET__;	
	
	@Before
	public void __initialization(){						
		//先判断浏览器是否是合适的
		this.checkUa();		
		
		//是否登录啦
        this.checkAuthentification();
        
		//登录信息获取啦
        this.getLoginAdmin();
        
        //检测当前的操作是否有权限，如果有权限才显示的
        //this.checkPermission();
        
        //获取有权限的菜单啦
        this.menus();   
        
        //一些基本的配置啦
        this.iconfigure();
	}
	
	/**
	 * 检测浏览器啊
	 * @author 粽子
	 */
	public void checkUa(){	
		if(!ua.isChrome() && !ua.isFirefox() && !ua.isSafari() && !ua.isOpera() && !ua.isIE9Up()){
			throw Util.redirect("Ua.index");    
		}
	}
	
	/**
	 * 判断是否登录
	 * @author 粽子
	 */
	public void checkAuthentification(){
		if(session.get("admin_username") == null || session.get("adminid") == null) {        	
			throw Util.redirect("Login.index");        	
        }
	}
	
	/**
	 * 获取登陆信息
	 * @author 粽子
	 */	
	public void getLoginAdmin(){
		String adminid = session.get("adminid");
		this.loginAdmin = adminsDao.findOneBy("adminid",adminid);
		context.renderArg("loginAdmin",loginAdmin);		
	}	
		
	/**
	 * 判断是否有权限啊，如果有权限才可以访问啊
	 * @author 粽子
	 */
	public boolean checkPermission(){
		//如果请求的action不在验证的列表里面，那么就不用验证啦
		if(this.noPermissonActions.contains(context.actionPath().trim())){
			return true;
		}
		
		if(permissionsLogic.checkPermission() == false){
			throw Util.redirect("Logout.index");
		}else{
			return true;
		}
	}	
	
	/**
	 * 获取权限菜单啦
	 * @return
	 */
	public void menus(){
		context.renderArg("menus",permissionsLogic.getAdminPermisionsMenus());
	}
	
	/**
	 * 一些基本的配置啦
	 * @author 粽子
	 */
	public void iconfigure(){
		//静态地址啦
        this.__ASSET__ = "/asset";
        context.renderArg("__ASSET__",this.__ASSET__);
        
        //不需要验证的地方啦
        this.noPermissonActions.add("com.zanha.javacmsframework.controller.admin.Index.clear");
        
        //权限控制
        context.renderArg("permissions",permissions);
	}
}